<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Ding;
use App\Services\DingTalkPush;
use EasyDingTalk\Kernel\Exceptions\InvalidArgumentException;
use Exception;
use Illuminate\Http\Request;
use EasyDingTalk\Application;
use Illuminate\Support\Str;
use Symfony\Component\HttpFoundation\Response;

class DingController extends Controller
{
    /**
     * @param Request $request
     * @return Response
     * @throws InvalidArgumentException
     */
    public function push(Request $request)
    {
        //http://xxx.top/api/ding/push?id=1
        //多钉钉通过携带公司参数的形式，读取对应配置后，与默认配置进行合并后实例化对象
        $ding = Ding::query()->findOrFail($request->get('id'));
        $app = new Application(array_merge(config('ding'), $ding->toArray()));
        $server = $app->server;
        //事件处理
        $server->push(function ($payload) {
            //
            $type = Str::camel($payload['EventType']);
            if (method_exists(DingTalkPush::class, $type)) {
                $push_server = new DingTalkPush($payload['CorpId']);
                $push_server->$type($payload);
            }
        });
        return $server->serve();
    }


    //机器人推送地址
    public function robot(Request $request)
    {
        //ReceiveMessageJob::dispatch($request->all());
        return response()->json();
    }
}


